#include<ros/ros.h>
#include<sensor_msgs/Joy.h>
#include<geometry_msgs/PointStamped.h>
#include<geometry_msgs/TransformStamped.h>
#include<geometry_msgs/PoseStamped.h>
#include<geometry_msgs/TwistStamped.h>
#include<geometry_msgs/Vector3Stamped.h>
#include <mavros_msgs/CommandBool.h>
#include <mavros_msgs/SetMode.h>
#include <mavros_msgs/State.h>
#include <uav/convert_mix.h>
#include <visualization_msgs/Marker.h>
#include <nav_msgs/Path.h>
#include <std_msgs/Float64.h>

//上升结束
int flag_pos=0;
//计数
int count_all=0;
int count_out=0;
//全局变量
geometry_msgs::Vector3Stamped input_,output_;
geometry_msgs::PoseStamped pose_out;
geometry_msgs::TwistStamped last_twist;
geometry_msgs::Vector3Stamped acc_cal;
double t,time_accel,time_begin;

//convert_.h函数

geometry_msgs::Vector3Stamped optimization(geometry_msgs::Vector3Stamped input,geometry_msgs::PoseStamped pose_,geometry_msgs::TwistStamped twst);
double testPos(geometry_msgs::PoseStamped pos);

//回调函数
mavros_msgs::State current_state;
void state_cb(const mavros_msgs::State::ConstPtr& msg){
    current_state = *msg;
}

geometry_msgs::PoseStamped current_pose;
void pose_cb(const geometry_msgs::PoseStamped::ConstPtr &msg1)
{
    current_pose=*msg1; 
}

geometry_msgs::TwistStamped current_twist;
void twist_cb(const geometry_msgs::TwistStamped::ConstPtr &msg2)
{
    current_twist= *msg2;
}

sensor_msgs::Joy joy_state;
void joy_cb(const sensor_msgs::Joy::ConstPtr &msg3)
{
    joy_state= *msg3;
    input_.vector.x=joy_state.axes[0];
    input_.vector.y=joy_state.axes[1];
    input_.vector.z=joy_state.axes[2];
    ROS_INFO("joy=%f,%f,%f",joy_state.axes[0],joy_state.axes[1],joy_state.axes[2]); 
}


int main(int argc, char** argv)
{
    ros::init(argc,argv,"ecbf_node");
    ros::NodeHandle nh;
    ros::Subscriber state_sub = nh.subscribe<mavros_msgs::State>
            ("mavros/state", 10, state_cb);
    ros::Subscriber  current_vel=nh.subscribe<geometry_msgs::TwistStamped>
            ("/mavros/local_position/velocity_local",10,twist_cb);
    ros::Subscriber local_pos=nh.subscribe<geometry_msgs::PoseStamped>
            ("mavros/local_position/pose",10,pose_cb);
    /* ros::Subscriber joy_sub=nh.subscribe<sensor_msgs::Joy>
            ("joy",10,joy_cb); */

    ros::Publisher marker_pub=nh.advertise<visualization_msgs::Marker>("marker",10);
    ros::Publisher path_pub = nh.advertise<nav_msgs::Path>("trajectory", 10);
    ros::Publisher point_pub = nh.advertise<geometry_msgs::PointStamped>("point", 10);
    ros::Publisher pos_dst=nh.advertise<geometry_msgs::PoseStamped>
            ("mavros/setpoint_position/local",10); 
    ros::Publisher accel_pub=nh.advertise<geometry_msgs::Vector3Stamped>
            ("/mavros/setpoint_accel/accel",10); 
    ros::Publisher accecbfx_pub=nh.advertise<std_msgs::Float64>
            ("/accecbf_x",10);
    ros::Publisher accecbfy_pub=nh.advertise<std_msgs::Float64>
            ("/accecbf_y",10);
    ros::Publisher accecbfz_pub=nh.advertise<std_msgs::Float64>
            ("/accecbf_z",10);
    ros::Publisher accinx_pub=nh.advertise<std_msgs::Float64>
            ("/accin_x",10);
    ros::Publisher acciny_pub=nh.advertise<std_msgs::Float64>
            ("/accin_y",10);
    ros::Publisher accinz_pub=nh.advertise<std_msgs::Float64>
            ("/accin_z",10);
    ros::Publisher err_pub=nh.advertise<std_msgs::Float64>
            ("/errpub_",10);
    ros::Publisher time_pub=nh.advertise<std_msgs::Float64>
            ("/ecbftime",10);
    
    ros::ServiceClient arming_client = nh.serviceClient<mavros_msgs::CommandBool>
            ("mavros/cmd/arming");
    ros::ServiceClient set_mode_client = nh.serviceClient<mavros_msgs::SetMode>
            ("mavros/set_mode");


    //trajectory
    ros::Time current_time, last_time;
    current_time = ros::Time::now();
    last_time = ros::Time::now();

    nav_msgs::Path path;



    visualization_msgs::Marker box;
    box.header.frame_id="map";
    box.lifetime=ros::Duration(0);
    box.action=visualization_msgs::Marker::ADD;
    box.ns="cube";
    box.pose.orientation.w=1.0;
    box.id=2;
    box.type=visualization_msgs::Marker::CUBE;
    box.scale.x=3;
    box.scale.y=3;
    box.scale.z=1;
    box.pose.position.x=0;
    box.pose.position.y=0;
    box.pose.position.z=1.5;
    box.color.r = 1.0;
    box.color.a = 0.5;

    
    //边缘
    visualization_msgs::Marker line_list;
    line_list.header.frame_id="map";
    line_list.lifetime=ros::Duration(0);
    line_list.ns="lines";
    line_list.action = visualization_msgs::Marker::ADD;
    line_list.pose.orientation.w = 1.0;
    line_list.id = 2;
    line_list.type = visualization_msgs::Marker::LINE_LIST;
    line_list.scale.x = 0.01;
    line_list.scale.y=0.01;
    line_list.scale.z=0.01;

    // Line list is blue
    line_list.color.b = 1.0;
    line_list.color.a = 1;
    geometry_msgs::Point p1;
    p1.x=-1.5;
    p1.y=-1.5;
    p1.z=1;
    geometry_msgs::Point p2;
    p2.x=1.5;
    p2.y=-1.5;
    p2.z=1;
    geometry_msgs::Point p3;
    p3.x=1.5;
    p3.y=1.5;
    p3.z=1;
    geometry_msgs::Point p4;
    p4.x=-1.5;
    p4.y=1.5;
    p4.z=1;
    geometry_msgs::Point p5;
    p5.x=-1.5;
    p5.y=-1.5;
    p5.z=2;
    geometry_msgs::Point p6;
    p6.x=1.5;
    p6.y=-1.5;
    p6.z=2;
    geometry_msgs::Point p7;
    p7.x=1.5;
    p7.y=1.5;
    p7.z=2;
    geometry_msgs::Point p8;
    p8.x=-1.5;
    p8.y=1.5;
    p8.z=2;

    line_list.points.push_back(p1);
    line_list.points.push_back(p2);
    line_list.points.push_back(p2);
    line_list.points.push_back(p3);
    line_list.points.push_back(p3);
    line_list.points.push_back(p4);
    line_list.points.push_back(p4);
    line_list.points.push_back(p1);

    line_list.points.push_back(p5);
    line_list.points.push_back(p6);
    line_list.points.push_back(p6);
    line_list.points.push_back(p7);
    line_list.points.push_back(p7);
    line_list.points.push_back(p8);
    line_list.points.push_back(p8);
    line_list.points.push_back(p5);

    line_list.points.push_back(p1);
    line_list.points.push_back(p5);
    line_list.points.push_back(p2);
    line_list.points.push_back(p6);
    line_list.points.push_back(p3);
    line_list.points.push_back(p7);
    line_list.points.push_back(p4);
    line_list.points.push_back(p8);

    ros::Rate rate(20.0);

    while(ros::ok() && !current_state.connected)
    {
        ros::spinOnce();
        rate.sleep();
    }
    
    //位置控制
    pose_out.pose.position.x=0;
    pose_out.pose.position.y=0;
    pose_out.pose.position.z=1.5;
    //pose_out.pose.orientation=tf::createQuaternionMsgFromRollPitchYaw(0,0,0);
    input_.vector.x=1;
    input_.vector.y=0;
    input_.vector.z=0;

    for(int i=100;ros::ok()&&i>0;--i)
    {
        pos_dst.publish(pose_out);
        ros::spinOnce();
        rate.sleep();
    }

    mavros_msgs::SetMode offb_set_mode;
    offb_set_mode.request.custom_mode = "OFFBOARD";
    mavros_msgs::CommandBool arm_cmd;
    arm_cmd.request.value = true;
    ros::Time last_request = ros::Time::now();

    while(ros::ok())
    {

        path.header.stamp = current_time;
        path.header.frame_id = "map";
        marker_pub.publish(line_list);
        line_list.header.stamp=ros::Time::now();
        marker_pub.publish(box);
        box.header.stamp=ros::Time::now();

        geometry_msgs::PointStamped this_point_stamped;
        this_point_stamped.header.frame_id="map";

        this_point_stamped.point.x = current_pose.pose.position.x;
        this_point_stamped.point.y = current_pose.pose.position.y;
        this_point_stamped.point.z = current_pose.pose.position.z;

        point_pub.publish(this_point_stamped);

        if(current_state.mode!="OFFBOARD"&&
        (ros::Time::now()-last_request>ros::Duration(5.0)))
        {
            if(set_mode_client.call(offb_set_mode)&&
            offb_set_mode.response.mode_sent)
            {
                ROS_INFO("Offboard enabled");
            }
            last_request=ros::Time::now();
        }
        else
        {
            if(!current_state.armed&&
            (ros::Time::now()-last_request>ros::Duration(5.0)))
            {
                if(arming_client.call(arm_cmd)&&
                arm_cmd.response.success)
                {
                    ROS_INFO("Vehicle armed");
                }
                last_request=ros::Time::now();
            }
        }

        //spinOnce放在两次操作中
        if(flag_pos==0)
        {
            pos_dst.publish(pose_out);
            ros::spinOnce();
            rate.sleep();
            if(current_pose.pose.position.z=1.5)
            {
                last_twist=current_twist;
                time_begin=ros::Time::now().toSec();
                flag_pos=1;
            }
        } 
        if(flag_pos==1)
        { 
            ros::spinOnce();
            rate.sleep();
            /* time_accel=ros::Time::now().toSec()-time_begin;

            if(time_accel<=4)
            {
                input_.vector.x=0.7;
                input_.vector.y=0;
                input_.vector.z=0.7;
            }
            if(time_accel>4&&time_accel<=8)
            {
                input_.vector.x=0;
                input_.vector.y=0;
                input_.vector.z=-1;
            }
            if(time_accel>8&&time_accel<=12)
            {
                input_.vector.x=-2;
                input_.vector.y=1;
                input_.vector.z=0;
            }
            if(time_accel>12)
            {
                input_.vector.x=0;
                input_.vector.y=0;
                input_.vector.z=1;
            } */

            double dist;
            dist=testPos(current_pose);
            
            if(dist<0)
            {
                ROS_INFO("out of range");
                count_out++;
            }
            count_all++;
            ROS_INFO("detected for %d times, out for %d times",count_all,count_out);
            
            std_msgs::Float64 errdist;
            errdist.data=dist;
            err_pub.publish(errdist);
            
            //pose发布

            geometry_msgs::PoseStamped this_pose_stamped;
        
            this_pose_stamped=current_pose;
        
            this_pose_stamped.header.stamp = current_time;
            this_pose_stamped.header.frame_id = "map";
            path.poses.push_back(this_pose_stamped);

            path_pub.publish(path);
        
            last_time = current_time;

            std_msgs::Float64 accinx,acciny,accinz;
            accinx.data=input_.vector.x;
            acciny.data=input_.vector.y;
            accinz.data=input_.vector.z;
            accinx_pub.publish(accinx);
            acciny_pub.publish(acciny);
            accinz_pub.publish(accinz);

            double t_begin=ros::Time::now().toSec();
            ROS_INFO("t_begin=%f",t_begin);


            //output_=optimization(input_,current_pose,current_twist);
            output_=input_;

            double t_end=ros::Time::now().toSec();
            ROS_INFO("t_end=%f",t_end);

            std_msgs::Float64 durati;
            durati.data=t_end-t_begin;
            time_pub.publish(durati);
            

            std_msgs::Float64 accecbfx,accecbfy,accecbfz;
            accecbfx.data=output_.vector.x;
            accecbfy.data=output_.vector.y;
            accecbfz.data=output_.vector.z;
            accecbfx_pub.publish(accecbfx);
            accecbfy_pub.publish(accecbfy);
            accecbfz_pub.publish(accecbfz);

            accel_pub.publish(output_);
        } 
    }
    return 0;


}